import React, { useEffect, useState, useRef } from 'react'
import { NavBar, Toast } from 'antd-mobile'
import { useNavigate, Link } from 'react-router-dom'
import styles from './index.module.css'
import { getMapAreaAPI, getHouseListAPI } from '../../apis/map'
import HouseItem from '../../components/houseItem'
import { baseURL } from '../../utils/request'

const labelStyle = {
    cursor: 'pointer',
    border: '0px solid rgb(255,0,0)',
    padding: '0px',
    whiteSpace: 'nowrap',
    fontSize: '12px',
    color: 'rgb(255,255,255)',
    textAlign: 'center',
    zIndex: '1500'
}
export default function Map() {
    let map
    const navigate = useNavigate()
    const mapRef = useRef(null)
    const labelRef = useRef(null)
    const [isShow, setIsShow] = useState(0)
    const [housesList, setHousesList] = useState([])
    async function renderOverlays(id) {
        let cur
        try {
            cur = Toast.show({
                icon: 'loading',
                content: '加载中…',
            })
            const res = await getMapAreaAPI(id)
            // console.log(res.body)
            const { nextZoom, type } = getTypeAndZoom()
            res.body.forEach(item => {
                createOverlays(item, nextZoom, type)
            })
            cur.close()
        } catch (e) {
            cur.close()
        }

    }
    async function getHouseList(id) {
        let cur
        try {
            cur = Toast.show({
                icon: 'loading',
                content: '加载中…',
                duration: 0
            })
            const res = await getHouseListAPI(id)
            setHousesList(res.body.list)
            cur.close()
        } catch (e) {
            cur.close()
        }

    }
    function createOverlays(item, zoom, type) {
        const { label: areaName, coord: { latitude, longitude }, count, value } = item
        const areaPoint = new window.BMapGL.Point(longitude, latitude)
        if (type === 'circle') {
            createCircle(areaPoint, areaName, count, value, zoom)
        } else {
            createRect(areaPoint, areaName, count, value)
        }
    }
    function createCircle(areaPoint, areaName, count, id, zoom) {
        let opts = {
            position: areaPoint, // 指定文本标注所在的地理位置
            offset: new window.BMapGL.Size(-35, -35) // 设置文本偏移量
        };

        // 创建文本标注对象
        let label = new window.BMapGL.Label('', opts);
        label.id = id
        label.setContent(`
        <div class="${styles.bubble}">
            <p class="${styles.name}">${areaName}</p>
            <p>${count}套</p>
        </div>
        `)
        // 自定义文本标注样式
        label.setStyle(labelStyle);
        label.addEventListener('click', (e) => {
            renderOverlays(id)
            // console.log('点击了', e)

            map.centerAndZoom(areaPoint, zoom)
            map.clearOverlays()
        })
        map.addOverlay(label)
    }
    useEffect(() => {
        const { label, value } = JSON.parse(localStorage.getItem('hkzf_city'))
        map = new window.BMapGL.Map("container")
        //创建地址解析器实例
        const myGeo = new window.BMapGL.Geocoder()
        // console.log(myGeo)
        myGeo.getPoint(
            label,
            async point => {
                if (point) {
                    map.centerAndZoom(point, 11);
                    map.addControl(new window.BMapGL.ZoomControl())
                    map.addControl(new window.BMapGL.ScaleControl())
                    renderOverlays(value)
                    // res.body.forEach(item => {
                    //     const { label: areaName, coord: { latitude, longitude }, count, value } = item
                    //     const areaPoint = new window.BMapGL.Point(longitude, latitude)
                    //     let opts = {
                    //         position: areaPoint, // 指定文本标注所在的地理位置
                    //         offset: new window.BMapGL.Size(-35, -35) // 设置文本偏移量
                    //     };

                    //     // 创建文本标注对象
                    //     let label = new window.BMapGL.Label('', opts);
                    //     label.id = value
                    //     label.setContent(`
                    //     <div class="${stlyes.bubble}">
                    //         <p class="${stlyes.name}">${areaName}</p>
                    //         <p>${count}套</p>
                    //     </div>
                    //     `)
                    //     // 自定义文本标注样式
                    //     label.setStyle(labelStyle);
                    //     map.addOverlay(label);
                    //     label.addEventListener('click', () => {
                    //         console.log('点击了', label.id)
                    //         map.centerAndZoom(areaPoint, 13)
                    //         map.clearOverlays()
                    //     })
                    //     map.addOverlay(label)
                    // });

                }
            }, label)
        mapRef.current = map

    }, [])
    useEffect(() => {
           mapRef.current && mapRef.current.removeEventListener('movestart')
            //isShow改变后需要重新绑定监听事件，否则访问的isShow还是之前的值
            mapRef.current.addEventListener('movestart', () => {
                console.log('move'+isShow)
                if (isShow) {
                    setIsShow(0)
                }
            })
        // console.log('move' + isShow)
    }, [isShow])
    function createRect(areaPoint, areaName, count, id) {
        let opts = {
            position: areaPoint, // 指定文本标注所在的地理位置
            offset: new window.BMapGL.Size(-50, -28) // 设置文本偏移量
        };

        // 创建文本标注对象
        let label = new window.BMapGL.Label('', opts);
        label.id = id
        // 设置房源覆盖物内容
        label.setContent(`
            <div class="${styles.rect}">
                <span class="${styles.housename}">${areaName}</span>
                <span class="${styles.housenum}">${count}套</span>
                <i class="${styles.arrow}"></i>
            </div>
         `)
        // 自定义文本标注样式
        label.setStyle(labelStyle);
        map.addOverlay(label)
        label.addEventListener('click', (e) => {
            // console.log('小区被点击了-before', isShow)
            setIsShow(1)
            // console.log('小区被点击了-after', e)
            // const target = e.domEvent.changedTouches[0]
            // map.panBy(
            //     window.innerWidth / 2 - target.clientX,
            //     (window.innerHeight - 330) / 2 - target.clientY
            // )
            getHouseList(id)
        })

    }
    function getTypeAndZoom() {
        const zoom = map.getZoom()
        let nextZoom, type
        console.log('缩放级别', zoom)
        if (zoom >= 10 && zoom < 12) {
            nextZoom = 13
            type = 'circle'
        } else if (zoom>=12 && zoom <= 13) {
            nextZoom = 15
            type = 'circle'
        } else if (zoom > 13) {
            type = 'rect'
        }
        return {
            nextZoom,
            type
        }
    }
    // 封装渲染房屋列表的方法
    function renderHousesList() {
        return housesList.map(item => (
            <HouseItem
                onClick={() => navigate(`/detail/${item.houseCode}`)}
                key={item.houseCode}
                src={baseURL + item.houseImg}
                title={item.title}
                desc={item.desc}
                tags={item.tags}
                price={item.price}
            />
        ))
    }

    return (
        <div className={styles.map}>
            <NavBar onBack={() => navigate(-1)} style={{ backgroundColor: '#f6f6f6' }}>
                地图找房
            </NavBar>
            <div id='container' className={styles.container} />
            {/* 房源列表 */}
            {/* 添加 styles.show 展示房屋列表 */}
            <div
                className={[
                    styles.houseList,
                    isShow ? styles.show : ''
                ].join(' ')}
            >
                <div className={styles.titleWrap}>
                    <h1 className={styles.listTitle}>房屋列表</h1>
                    <Link className={styles.titleMore} to="/home/list">
                        更多房源
                    </Link>
                </div>

                <div className={styles.houseItems}>
                    {/* 房屋结构 */}
                    {renderHousesList()}
                </div>
            </div>

        </div>
    )
}
